<template>
  <div class="app-container">
    <div style="display: flex;">
      <!--侧边部门数据-->
      <div style="width: 420px;">
        <div class="head-container" />
        <div v-if="containerOptions.length>0" style="margin: -8px 0 10px 0;">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-button type="primary" size="mini" icon="el-icon-download" style="width: 100%;" disabled>导入</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" size="mini" icon="el-icon-upload2" style="width: 100%;" disabled>导出</el-button>
            </el-col>
          </el-row>
        </div>
        <!-- show-checkbox隐藏这句 需要时加上即可 -->
        <div class="tree">
          <el-tree
            ref="tree"
            :data="containerOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :highlight-current="true"
            :default-expand-all="true"
            draggable
            :allow-drag="allowDrag"
            :allow-drop="allowDrop"
            node-key="id"
            @node-drag-start="handleDragStart"
            @node-drop="handleDrop"
            @check="handleCheckChange"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <!-- 类型为分类 显示操作icon-->
              <span v-if="data.type === 'category' || data.type === 'component'">
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link">
                    <i class="el-icon-more" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <!-- 类型为分类 可以新增下级 -->
                    <el-dropdown-item v-if="data.type === 'category'" @click.native="addChildNode(node, data)">新增下级</el-dropdown-item>
                    <!-- 自定义节点可以编辑、删除 -->
                    <el-dropdown-item v-if="data.type === 'component'" @click.native="editChildNode(data)">编辑</el-dropdown-item>
                    <el-dropdown-item v-if="data.type === 'component'" @click.native="handleDeleteNode(data)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <!--用户数据-->
      <div style="flex:1;margin-left: 20px;width: 0px;">
        <!--工具栏-->
        <el-row>
          <el-button type="primary" size="mini" icon="el-icon-tickets" style="margin: 2px 0px 10px;" @click="toggleShowLog">日志</el-button>
        </el-row>
        <!-- <div v-if="levels" class="top">{{ levels }}</div> -->
        <!--表单组件-->
        <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
          <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
            <el-form-item label="说明" prop="description" class="form-item-margin">
              <el-input v-model="form.description" type="textarea" :maxlength="500" :show-word-limit="true" :autosize="{ minRows: 4, maxRows: 10 }" class="el-input-min-width'" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 180px)" :data="crud.data" size="small" :span-method="mergeCell" style="width: 100%">
          <el-table-column prop="typeName" label="标准" min-width="10%" />
          <el-table-column prop="level" label="等级" min-width="10%" />
          <el-table-column prop="description" label="说明" min-width="50%" />
          <el-table-column prop="updateUser.nickName" label="更新者" min-width="10%" />
          <el-table-column prop="updateTime" label="更新时间" min-width="10%" />
          <el-table-column v-if="checkPer(['admin','standardComponentLevel:edit'])" label="操作" width="150px" align="center">
            <template slot-scope="scope">
              <el-button v-permission="permission.edit" :loading="crud.status.cu === 2" size="mini" type="text" @click="crud.toEdit(scope.row)"><svg-icon icon-class="icon-edit" /> 编辑 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <LogDialog :log-type="logType" :dialog-visible.sync="showLog" />
  </div>
</template>

<script>
import crudStandardComponentLevel, { queryAllByGroup, addNode, editNode, delNode, exchangeUpdateComponentSorted } from '@/api/modelQuality/componentManage'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import LogDialog from '@/components/logManage/dialog'
import { COMPONENT_LOG } from '@/utils/log'

const defaultForm = { levelId: null, componentId: null, type: null, level: null, description: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'ComponentManage',
  components: { LogDialog },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['standard_component_category'],
  cruds() {
    return CRUD({ title: '构件管理', url: 'api/standardComponentLevel', queryOnPresenterCreated: false, crudMethod: { ...crudStandardComponentLevel }})
  },
  data() {
    return {
      levels: '', // 所有层级
      componentId: '',
      containerOptions: [],
      copyTreeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      permission: {
        edit: ['admin', 'standardComponentLevel:edit']
      },
      rules: {
        description: [
          { required: false, message: '说明不能为空', trigger: 'blur' }
        ]
      },
      showLog: false,
      logType: COMPONENT_LOG
    }
  },
  created() {
    // 查询左侧树
    this.queryAllByGroup()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.query.componentId = this.componentId
      return true
    },
    // 查询左侧树
    queryAllByGroup() {
      queryAllByGroup().then((response) => {
        this.containerOptions = response
      })
    },
    // 合并“标准”列
    mergeCell({ row, column, rowIndex, columnIndex }) {
      const spanArr = []
      let concat = 0
      this.crud.data.map((item, index) => {
        if (index === 0) {
          spanArr.push(1)
        } else {
          // 第一列需合并相同内容的判断条件
          if (item.typeName === this.crud.data[index - 1].typeName) {
            spanArr[concat] += 1
            spanArr.push(0)
          } else {
            spanArr.push(1)
            concat = index
          }
        }
      })
      // 需要合并的列号 第1列 不可改
      if (columnIndex === 0) {
        const _row = spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    // 切换节点
    handleNodeClick(data) {
      // 清空数据
      this.crud.data = []
      // 当类型是component时 叶子节点可以触发右侧列表
      if (data.type === 'component') {
        // 选中的层级节点
        this.levels = '全部/' + this.dict.label.standard_component_category[data.parentId] + '/' + data.name
        this.componentId = data.id
        this.crud.toQuery()
      } else if (data.type === 'category') {
        // 选中的层级节点
        this.levels = '全部/' + data.name
      } else {
        // 选中的层级节点
        this.levels = '全部'
      }
    },
    // 新增下级节点
    addChildNode(node, data) {
      this.$prompt('请输入节点名称', '新增', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputErrorMessage: '输入不能为空',
        inputValidator: (value) => {
          if (!value) {
            return '输入不能为空'
          } else if (value.length > 20) {
            return '输入不能超过20个字符'
          }
        }
      }).then(({ value }) => {
        const param = {
          name: value,
          parentId: data.id
        }
        addNode(param).then(res => {
          this.$message.success('新增成功')
          this.queryAllByGroup()
        })
      }).catch(() => {})
    },
    // 编辑节点
    editChildNode(data) {
      this.$prompt('请输入节点名称', '编辑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: data.name,
        closeOnClickModal: false,
        inputErrorMessage: '输入不能为空',
        inputValidator: (value) => {
          if (!value) {
            return '输入不能为空'
          } else if (value.length > 20) {
            return '输入不能超过20个字符'
          }
        }
      }).then(({ value }) => {
        const param = {
          id: data.id,
          parentId: data.parentId,
          name: value
        }
        editNode(param).then(res => {
          this.$message.success('编辑成功')
          this.$set(data, 'name', value)
        })
      }).catch(() => {})
    },
    // 删除节点
    handleDeleteNode(data) {
      this.$confirm(`确定删除'${data.name}'节点, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        delNode([data.id]).then(res => {
          this.$message.success('删除成功')
          this.queryAllByGroup()
          this.crud.toQuery()
          this.levels = ''
        })
      }).catch(() => {})
    },
    // 选中复选框
    handleCheckChange(data, checked, indeterminate) {
      console.log(checked.checkedNodes)
    },
    toggleShowLog() {
      this.showLog = !this.showLog
    },
    // 判断节点能否被拖拽 目前仅叶子节点可拖拽
    allowDrag(draggingNode) {
      return draggingNode.data.type === 'component'
    },
    // 拖拽时判断目标节点能否被放置
    allowDrop(draggingNode, dropNode, type) {
      // 仅叶子节点可以拖拽
      if (draggingNode.data.type !== 'component' || dropNode.data.type !== 'component' || draggingNode.parent.id !== dropNode.parent.id) {
        return false
      }
      if (draggingNode.nextSibling === undefined) {
        return type === 'prev'
      } else if (dropNode.nextSibling === undefined) {
        return type === 'next'
      } else if (draggingNode.nextSibling.id !== dropNode.id) {
        return type === 'prev'
      } else {
        return type === 'next'
      }
    },
    // 拖拽开始前克隆数据
    handleDragStart() {
      this.copyTreeList = JSON.parse(JSON.stringify(this.containerOptions))
    },
    // 拖拽成功完成时触发的事件
    handleDrop(draggingNode, dropNode, dropType, ev) {
      this.$confirm(
        `是否将 "${draggingNode.label}" 移动到 "${dropNode.label}"${
          dropType === 'before' ? '之前' : dropType === 'after' ? '之后' : '下'
        }?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        }
      )
        .then(() => {
          exchangeUpdateComponentSorted(dropNode.parent.data.children).then(res => {
            this.$message({
              type: 'success',
              message: '移动成功'
            })
            this.queryAllByGroup()
            this.crud.data = []
            this.levels = ''
          })
        })
        .catch(() => {
          this.containerOptions = this.copyTreeList
          this.crud.data = []
          this.levels = ''
          this.$message({
            type: 'info',
            message: '取消移动'
          })
        })
    }
  }
}
</script>

<style scoped>
  .top {
    margin-bottom: 12px;
    color: #686868;
    font-size: 15px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .tree{
    overflow: auto;
    height: calc(80vh - 10px);
    background-color: #fff;
  }
  div /deep/ .el-table--border::after,
  div /deep/ .el-table--group::after,
  div /deep/ .el-table::before {
      background-color: transparent;
  }
</style>
